package com.xszx.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xszx.config.PageRequest;
import com.xszx.dao.UserDao;
import com.xszx.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    private UserDao userDao;

    public void addUser(User user) {
        String encryptedPassword = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(encryptedPassword);
        userDao.addUser(user);
    }

    public void delUser(Integer id) {
        userDao.delUser(id);
    }

    public void updateUser(User user) {
        // 对输入的密码进行MD5加密
        String encryptedPassword = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(encryptedPassword);
        userDao.updateUser(user);
    }

    public PageInfo<User> getUserListWithPage(PageRequest pageRequest) {
        PageHelper.startPage(pageRequest.getPage(), pageRequest.getSize());
        List<User> userList = userDao.getUserListWithPage(pageRequest);
        return new PageInfo<>(userList);
    }

    public User login(String username, String password) {
        User user = userDao.findByLoginName(username);
        if (user != null) {
            user.setLoginName(username);
            // 对输入的密码进行MD5加密
//            System.out.println(user);
            String encryptedPassword = DigestUtils.md5DigestAsHex(password.getBytes());
            // 验证密码
            if (encryptedPassword.equals(user.getPassword())) {
                return user;
            }else {
                System.err.println("密码错误");
            }
        }
        System.err.println("用户名不存在");
        return null;
    }

    public User findByLoginName(String username) {
        return userDao.findByLoginName(username);
    }

    public boolean register(User user) {
        String encryptedPassword = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(encryptedPassword);
        user.setRid(4);
        userDao.register(user);
        return true;
    }

    public User findByUid(Integer uid) {
        return userDao.findByUid(uid);
    }

}
